//2021-06-02 xia.he 用户操作
const {QueryTypes, Sequelize} = require('sequelize');
const {sign} = require('jsonwebtoken');
const Task_admin = require('../models/task_admin')
const statusCode = require('../utils/status-code');//code返回

/**
 * 登录获
 * @param ctx
 * @returns {Promise<{msg: *, code: number, data: *}>}
 */
async function loginInit(ctx) {
    let {userId, name} = ctx.request.body;
    try {
        //缓存365天
        const token = sign({
            name: name,
            userId: userId,
        }, 'jwtSecret', {expiresIn: '365d'});
        return ctx.body = statusCode.SUCCESS_200("查询成功", {token: token})
    } catch (e) {
        console.log('loginInit:%s', e.toString());
        ctx.body = statusCode.ERROR_400(e.toString());
        throw new Error(e);
    }
}

/**
 * 获取用户任务列表
 * @param ctx
 * @returns {Promise<{msg: *, code: number, data: *}>}
 */
async function getTaskList(ctx) {
    let {userId} = ctx.request.body;
    try {
        let res = await findTaskList(userId);
        if (res) return ctx.body = statusCode.SUCCESS_200("查询成功", res)
        ctx.body = statusCode.SUCCESS_200("查询成功", null);
    } catch (e) {
        console.log('loginInit:%s', e.toString());
        ctx.body = statusCode.ERROR_400(e.toString());
        throw new Error(e);
    }
}


/**
 * 添加设置内容
 * @param ctx
 * @returns {Promise<{msg: *, code: number, data: *}>}
 */
async function saveUser(ctx) {
    let {userId, name, task, frequency, chart, line, switchTime} = ctx.request.body;
    try {
        //查询
        let res = await findUser(userId);
        if (res) {
            await Task_admin.update({
                userId: userId,
                name: name,
                task: task,
                frequency: frequency,
                chart: chart,
                line: line,
                switchTime: switchTime,
                updateTime: Sequelize.literal('CURRENT_TIMESTAMP')
            }, {where: {userId: userId}});
        } else {
            await Task_admin.create({
                userId: userId,
                name: name,
                task: task,
                frequency: frequency,
                chart: chart,
                line: line,
                switchTime: switchTime
            });
        }
        ctx.body = statusCode.SUCCESS_200("保存成功");
    } catch (e) {
        console.log('saveUser:%s', e.toString());
        ctx.body = statusCode.ERROR_400(e.toString());
        throw new Error(e);
    }
}

/**
 * 获取用户设置
 * @param ctx
 * @returns {Promise<{msg: *, code: number, data: *}>}
 */
async function getUser(ctx) {
    let {userId} = ctx.request.body;
    try {
        let res = await findUser(userId);
        if (res) {
            let result = await findTaskList(userId);
            let taskList = [];
            if (result.length > 0 && res.task) {
                let array = JSON.parse(res.task);
                for (let i = 0; i < array.length; i++) {
                    let obj = _.findWhere(result, {idcId: array[i].idcId});
                    if (obj) {
                        taskList.push(obj)
                    }
                }
                let task = ""
                if (taskList.length > 0) {
                    task = JSON.stringify(taskList)
                }
                //把以前创建的任务,替换为现在正在监测的,停止的就没了
                await Task_admin.update({
                    task: task,
                }, {where: {userId: userId}});
                res.task = JSON.stringify(taskList);
            } else {
                res.task = "";
            }
            return ctx.body = statusCode.SUCCESS_200("查询成功", res);
        }
        ctx.body = statusCode.SUCCESS_200("查询成功", "");
    } catch (e) {
        console.log('getUser:%s', e.toString());
        ctx.body = statusCode.ERROR_400(e.toString());
        throw new Error(e);
    }
}

/**
 * 公共查询
 * @param ctx
 * @param userId
 * @param name
 * @returns {Promise<*|null>}
 */
async function findUser(userId) {
    try {
        let res = await Task_admin.find({where: {userId: userId}, raw: true});
        if (res) {
            return res
        }
        return null
    } catch (e) {
        console.log('findUser:%s', e.toString());
        throw new Error(e);
    }
}

/**
 *查询该任务是否处于激活状态
 * @param ctx
 * @returns {Promise<void>}
 */
async function findUse(ctx) {
    let {task_id} = ctx.request.body;
    try {
        let sql = "SELECT COUNT(1) as state  FROM task WHERE task_id=:task_id AND state=0 AND delete_flag=0";
        let res = await idcSequelize.query(sql, {
            replacements: {task_id: task_id},
            type: QueryTypes.SELECT
        })

        ctx.body = statusCode.SUCCESS_200("查询成功", res[0])

    } catch (e) {
        console.log('findUse:%s', e.toString());
        ctx.body = statusCode.ERROR_400(e.toString());
        throw new Error(e);
    }
}

/**
 * 公共查询用户任务列表
 * @param ctx
 * @param userId
 * @returns {Promise<void>}
 */
async function findTaskList(userId) {
    try {
        let sql = "";
        //判断是不是admin账号 查询所有用户ping任务
        if (userId === '1') {
            sql = "SELECT i.idc idcIp, t.rate ,t.task_id, CONCAT( t.task_id, '-', i.id ) idcId,CONCAT(t.`name`,'-',i.`name`) idcName FROM task t,task_idc i WHERE  t.task_type=1 AND i.task_id = t.task_id AND t.state = 0 AND t.delete_flag = 0 AND i.state = 1 AND i.delete_flag = 0   ORDER BY i.create_time desc";
        } else {
            sql = "SELECT i.idc idcIp, t.rate ,t.task_id, CONCAT( t.task_id, '-', i.id ) idcId,CONCAT(t.`name`,'-',i.`name`) idcName FROM task t,task_idc i WHERE  t.task_type=1 AND i.task_id = t.task_id AND t.state = 0 AND t.delete_flag = 0 AND i.state = 1 AND i.delete_flag = 0 AND t.user_id  IN ( SELECT USER_ID FROM sys_user WHERE org_id IN ( SELECT org_id FROM sys_user WHERE user_id = :userId ) ) ORDER BY i.create_time desc";
        }

        let res = await idcSequelize.query(sql,
            {
                replacements: {userId: userId},
                type: QueryTypes.SELECT
            }
        );
        if (res) return res;
        return null;
    } catch (e) {
        console.log('findaskList:%s', e.toString());
        throw new Error(e);
    }
}

module.exports = {loginInit, saveUser, getUser, getTaskList, findUse}